<!doctype html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=no">
    <title>签名板</title>
    <link th:href="@{/res/css/default.css}" rel="stylesheet">
</head>
<body>
<div class="top-block">
    <!-- 画布容器及画布配置 -->
    <div class="js-signature" data-width="600" data-height="280" data-border="1px solid #333" data-line-color="#000" data-line-width="3" data-auto-fit="true"></div>
    <p style="display: flex; justify-content: center">
        <button id="clearBtn" onclick="clearCanvas();">清除</button>&nbsp;
        <button id="saveBtn" onclick="saveSignature();" disabled>保存</button>
    </p>
</div>
<div class="gap-line"></div>
<div class="bottom-block hide">
    <div id="signature"></div>
    <p><button id="downBtn" onclick="downloadImg()">下载</button></p>
    <div id="downloadData"></div>
</div>
<script src="https://www.jq22.com/jquery/jquery-1.10.2.js"></script>
<script th:src="@{/res/js/jq-signature.js}"></script>
<script th:src="@{/res/bonorsoft/js/william-boot.js}"></script>
<script type="text/javascript">
    //初始化插件
    $(document).on('ready', function() {
        if($('.js-signature').length) {
            $('.js-signature').jqSignature();
        }
    });

    // 将“保存”按钮设为可用
    $('.js-signature').eq(0).on('jq.signature.changed', function() {
        $('#saveBtn').attr('disabled', false);
    });

    //清空画布
    function clearCanvas() {
        $('.js-signature').eq(0).jqSignature('clearCanvas');
        $('#saveBtn').attr('disabled', true);
        $('.bottom-block').hide();
    }

    //保存签名
    function saveSignature() {
        $('#signature').empty();
        let dataUrl = $('.js-signature').eq(0).jqSignature('getDataURL');
        let img = $('<img>').attr('src', dataUrl).attr('class', 'sign-img');
        $('#signature').append($('<p>').text("生成的签名:")).append(img);
        $('.bottom-block').show();
    }

    //下载签名图片
    function downloadImg() {
        $('#downloadData').empty();
        let signImgUrl = $('#signature img').attr('src');
        let blobObj = dataUrlToBlob(signImgUrl);
        let aEl = document.createElement('a');
        aEl.download = 'test.png';
        aEl.href = URL.createObjectURL(blobObj);
        $('#downloadData').append(aEl).hide();
        aEl.click();
    }

    /**
     * 将图片base64地址转为blob文件对象
     */
    function dataUrlToBlob(dataUrl) {
        var arr = dataUrl.split(','),
            mime = arr[0].match(/:(.*?);/)[1],
            bstr = atob(arr[1]),
            n = bstr.length,
            u8arr = new Uint8Array(n);
        while (n--) {	u8arr[n] = bstr.charCodeAt(n); }
        return new Blob([u8arr], { type: mime });
    }
</script>
</body>
</html>
